const { getRecordByUserId, getUserInfoByUserId } = require('../dota2api/index')
const dota2helper = require('./dota2helper')

const monitorGameMap = {}

// 监控战绩
function getMonitorRecord(userId) {
  return new Promise((resolve, reject) => {
    getRecordByUserId(userId, 1).then(async res => {
      let msg = ''
      if (res.length !== 0) {
        const timeNow = new Date().getTime()
        for (let index = 0; index < res.length; index++) {
          let recentMatchTime = (res[index].start_time + res[index].duration) * 1000
          let time = timeNow - recentMatchTime
          console.log(`${userId}最近一场比赛${formatTime(time)}`)
          if (time < 360000) {
            console.log(`${userId}检测到最近一小时内有比赛`)
            const isRead = await hasMonitorGame({ userId, matchId: res[index].match_id })
            if (!isRead) {
              console.log(`${userId}检测到有新比赛`)
              const userInfo = await getUserInfoByUserId(userId)
              const tierLevel = await dota2helper.getRankTier(userInfo.rank_tier, userInfo.leaderboard_rank)
              const hero = await dota2helper.getHeroName(res[index].hero_id)
              msg +=`在${formatTime(time)}结束的[${dota2helper.getPartSize(res[index].party_size)}][${dota2helper.getGameMode(res[index].game_mode)}][${dota2helper.getLobbyType(res[index].lobby_type)}]比赛中[${userInfo.profile.personaname}]${tierLevel}使用[${hero}]拿下了[${res[index].kills}]个人头[${res[index].assists}]个助攻,但是死了[${res[index].deaths}]次`
            }
          }
        }
      }
      resolve(msg)
    }).catch(e => {
      reject(e)
    })
  })
}

function hasMonitorGame({userId, matchId}){
    return new Promise((resolve) =>{
      if(monitorGameMap[userId]){
        if(monitorGameMap[userId].includes(matchId)){
          resolve(true)
        }else{
          monitorGameMap[userId].push(matchId)
          resolve(false)
        }
      }else{
        monitorGameMap[userId] = [matchId]
        resolve(false)
      }
    })
}

function formatTime(time) {
  const minutes = Math.floor(time / (60 * 1000))
  return `${minutes}分钟前`
}

module.exports = {
  getMonitorRecord
}